<template>
  <el-card style="margin-top:20px;width:100%;">
    <div slot="header" class="clearfix">
      <div id='about'>个人信息中心</div>
      <div class="sign" v-if="this.signpic" @click="tosign">
        已签约
      </div>
    </div>

    <div class="user-profile">
      <div class="box-center"  @click="closethumb">
        <pan-thumb   :image="user.avatar" :height="'100px'" :width="'100px'" :hoverable="false">
          
          <van-uploader :after-read="afterRead"  >
            <div @click="changephoto">点击修改</div>
          </van-uploader>
 <avatar-cutter v-if="showCutter&&os.isPc" @cancel="showCutter = false"  @modifyoriphoto="modifyoriphoto" @enter="uploadAvatar" return-type="url" :imgSrc="imgSrc"></avatar-cutter>

          <!-- {{ user.cardname }} -->
        </pan-thumb>
      </div>
      <div class="box-center">
        <div @click="showname" class="user-name text-center">{{ user.name }}<i class="van-icon van-icon-edit"><span style="font-size:12px">昵称</span></i></div>
        <div class="user-role text-center text-muted"></div>
        <!-- user.role | uppercaseFirst -->
      </div>
      <div v-if="this.signpic" class="userm">
                  <div class="userfile1" @click="toshipin" >
          我的短视频
        </div>
            <div class="userfile" @click="tozuopin" >
          我的作品
        </div>
          <div class="userfile2" @click="toorder" >
          我的订单
        </div>
        </div>
      
        <div class="nosign"  @click="tosign" v-else>
        立即签约入驻
      </div> 
    </div>

    <div class="user-bio">
      <div class="user-education user-bio-section">

        <div class="user-bio-section-header">
          <svg-icon icon-class="education" />
          <span  @click="showdesc">个人简介<i style="float:right" class="van-icon van-icon-edit">编辑</i></span>
        </div>

        <div class="user-bio-section-body">
          <div  @click="showdesc"  class="text-muted">{{user.introduction}}</div>
        </div>

      </div>
    </div>







      <!-- <div class="user-skills user-bio-section">
        <div class="user-bio-section-header"><svg-icon icon-class="skill" /><span>Skills</span></div>
        <div class="user-bio-section-body">
          <div class="progress-item">
            <span>Vue</span>
            <el-progress :percentage="70" />
          </div>
          <div class="progress-item">
            <span>JavaScript</span>
            <el-progress :percentage="18" />
          </div>
          <div class="progress-item">
            <span>Css</span>
            <el-progress :percentage="12" />
          </div>
          <div class="progress-item">
            <span>ESLint</span>
            <el-progress :percentage="100" status="success" />
          </div>
        </div>
      </div>-->

<van-popup   v-model="shownameinput" style="width:100%">
<van-cell-group>
  <!-- <span>请输入用户名：</span> -->
  <van-field @blur="updatecacheofaccount" ref="child" border v-model="user.name" placeholder="请输入用户名"  />
</van-cell-group>
</van-popup>

<van-popup   v-model="showdescinput" position="bottom">
<van-cell-group>
  <!-- <span>请输入用户名：</span> -->
  <van-field 
   @blur="updatecache" 
    type="textarea"
    placeholder="请输入个人简介"
    rows="10"
    autosize
     ref="desc" border v-model="user.introduction"/>
</van-cell-group>
</van-popup>






 <simple-cropper  :initParam="uploadParam" @successCallback="uploadAvatar" ref="cropper" v-if="showCutter&&!os.isPc" > 
 <!-- <img :src="userImg">  -->
 </simple-cropper>
 
  </el-card>
</template>

<script>
import PanThumb from "@/components/PanThumb";
import AvatarCutter from '@/components/avatar-cutter/avatar-cutter'
import SimpleCropper from '@/components/SimpleCropper/SimpleCropper'
// import clipper from '@/components/vueclipper/clipper'
// import ImageClipper from '@/components/imageClipper/imageClipper'

import Vue from 'vue';
import { Uploader } from 'vant';
import { Toast } from 'vant';
Vue.use(Toast);
Vue.use(SimpleCropper);
 
import { gettokens } from '@/api/user'
Vue.use(Uploader);
 
import { Field } from 'vant';

Vue.use(Field);
import { Popup } from 'vant';
import { Cell, CellGroup } from 'vant';

Vue.use(Cell).use(CellGroup);
Vue.use(Popup);
export default {
  components: { PanThumb,AvatarCutter,SimpleCropper},
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          name: "",
          email: "",
          avatar: "",
          roles: ""
        };
      }
    }
  },
  data(){
     return{
       os:{},
       imgSrcbase64:'',
       piccount:0,
       oriphoto:'',
       imgSrc:null,
       imgSrccut:null,
       showCutter: false, 
       signpic:"",
       shownameinput:false,
       showdescinput:false,
   uploader:null,
 uploadtag:1,
 photo:'',
 name:'',
 desc:'',
 uploadParam: { 
  fileType: 'recruit', // 其他上传参数 
  uploadURL: this.$dataURL + 'uploadAction/qcloudImg', // 上传地址 
  scale: 4 // 相对手机屏幕放大的倍数: 4倍 
  }, 
  userImg: this.$dataURL + 'test.png' 
     }


  },
    mounted(){
      var os = function() {  
     var ua = navigator.userAgent,  
     isWindowsPhone = /(?:Windows Phone)/.test(ua),  
     isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,   
     isAndroid = /(?:Android)/.test(ua),   
     isFireFox = /(?:Firefox)/.test(ua),   
     isChrome = /(?:Chrome|CriOS)/.test(ua),  
     isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),  
     isPhone = /(?:iPhone)/.test(ua) && !isTablet,  
     isPc = !isPhone && !isAndroid && !isSymbian;  
     return {  
          isTablet: isTablet,  
          isPhone: isPhone,  
          isAndroid : isAndroid,  
          isPc : isPc  
     };  
}();  
this.os=os;
console.log('os:')
console.log(this.os)
   document.getElementsByClassName('pan-thumb')[0].style.transform='unset';
   this.inituploader();
    if(sessionStorage.getItem('signpic')&&sessionStorage.getItem('signpic')!='null')
      {
        this.signpic=true;
        console.log("--------------------------")
        console.log(this.signpic)
      }else{
        this.signpic=false;
        console.log("--------------------------")
        console.log(this.signpic)
      }
  },



 
  methods:{
    // 上传头像 
 uploadChange (event) { 
  //  console.log("+++++++++开始upload");
  this.$refs['cropper'].uploadChange(event);
 }, 
 // 上传头像成功回调 
 uploadHandle (data) { 
  if (data.state === 'SUCCESS') { 
  this.userImg = this.form.headImgUrl = data.fileId 
  } 
 } ,
        // 从base64转化为file文件
    base64ToFile(base64Str, fileName) {
      const params = base64Str.split(',')
      const mime = params[0].match(/:(.*?)/)[1]
      const fileData = atob(params[1]) // 解码Base64
      let { length } = fileData
      const uint8Array = new Uint8Array(length)
      while (length) {
        length -= 1
        uint8Array[length] = fileData.charCodeAt(length)
      }
      return new File([uint8Array], fileName, { type: mime })
    },
    modifyoriphoto(neworifile)
    {
 //base
   this.imgSrc=neworifile;
   console.log('imgsrc修改完成')

    },
    toshipin(){
              this.$router.push({  
             path:'/files/shipinlist',   
      })

    },
        tozuopin(){
              this.$router.push({  
        path:'/files/zuopin',   
      })

    },
            toorder(){
              this.$router.push({  
               path:'/order/order',   
      })

    },

    tosign(){
      if(this.user.introduction==null){
          this.$toast('请输入个人简介')
      }else{
        this.$router.push({  
        path:'/documentation/index',   
      })
      }
    },


    showname(){

         this.shownameinput=true;
         this.$nextTick(function(){
  this.$refs.child.focus();
         })
       
    },
     showdesc(){

         this.showdescinput=true;
         this.$nextTick(function(){
  this.$refs.desc.focus();
         })
       
    },
     updatecache(){
  // this.$toast('更新完成')
            // this.user.introduction=this.desc;
            // this.user.avatar=this.photo;
            // this.user.name=this.name;
            // this.$store.commit('user/SET_NAME', this.user.name)
     
            // this.$store.commit('user/SET_INTRODUCTION', this.user.desc)
    this.$store.dispatch('user/addshop',{brandName:this.user.name,tradeMark:this.user.avatar,words:this.oriphoto,pictures:this.oriphoto,shopLongDescription:this.user.introduction})
        
  },
  updatecacheofaccount(){

            // this.user.introduction=this.desc;
            // this.user.avatar=this.photo;
            // this.user.name=this.name;
            // this.$store.commit('user/SET_NAME', this.user.name)
     
            // this.$store.commit('user/SET_INTRODUCTION', this.user.desc)
    this.$store.dispatch('user/addmerchant',{companyName:this.user.name})
    this.$store.dispatch('user/addshop',{brandName:this.user.name,tradeMark:this.user.avatar,words:this.oriphoto,pictures:this.oriphoto,shopLongDescription:this.user.introduction})


  },

    afterRead(event){   
      this.imgSrc=event.file;
      if(!this.os.isPc){
        this.showCutter=true;
        this.$nextTick(function(){
            this.uploadChange(event);
        })
          }
          else{

     const reader = new FileReader()
      reader.onload = () => {
        this.imgSrcbase64 = reader.result
          this.showCutter=true;
    }
    reader.readAsDataURL(this.imgSrc)


    }
    },
    inituploader() {
   
    var _this = this;
      this.uploader = new AliyunUpload.Vod({
        //分片大小默认1M，不能小于100K
        partSize: 1048576,
        //并行上传分片个数，默认5
        parallel: 5,
        //网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        //网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: function(uploadInfo) {
          // _this.$loadingshowjindu('0%')
          console.log(
            "onUploadStarted:" +
              uploadInfo.file.name +
              ", endpoint:" +
              uploadInfo.endpoint +
              ", bucket:" +
              uploadInfo.bucket +
              ", object:" +
              uploadInfo.object
          );
 
          gettokens({}).then(res => {
              console.log(res)

              console.log(this.uploader)
            _this.uploader.setSTSToken(
              uploadInfo,
              res.result.key,
              res.result.secret,
              res.result.token
            );
          });
        },
        // 文件上传成功
        onUploadSucceed: function(uploadInfo) {
               _this.piccount+=1;
                if(_this.piccount==2)
                {
       
             _this.$loadingshowjindu( "100%")
            _this.$loadingshowjindu( "")
                _this.$loadingclose();

                }
          console.log(
            "onUploadSucceed: " +
              uploadInfo.file.name +
              ", endpoint:" +
              uploadInfo.endpoint +
              ", bucket:" +
              uploadInfo.bucket +
              ", object:" +
              uploadInfo.object +
              uploadInfo +
              JSON.stringify(uploadInfo)
          );
          console.log("videoId:" + uploadInfo.videoId);
          
          if(uploadInfo.videoId==null)
          {

               var tempic="http://tests.sodataint.com/"+uploadInfo.object;
               
           
           
                if(uploadInfo.videoInfo.index=='1')
                {
               _this.photo=tempic;
               _this.user.avatar=_this.photo;
             _this.$store.commit('user/SET_AVATAR', _this.user.avatar)
         
                                console.log("index:"+uploadInfo.videoInfo.index)

               console.log("==============================="+tempic)
                }
                else
                {
                  console.log('tempic:'+tempic)
                   _this.oriphoto=tempic;
                  console.log("index:"+uploadInfo.videoInfo.index)

               console.log("==============================="+tempic)
                }
                if(_this.piccount==2)
                   _this.updatecache();

              
         
              //  _this.imgSrc = tempic;
               
                
          }
           
        },
        // 文件上传失败
        onUploadFailed: function(uploadInfo, code, message) {
          console.log(
            "onUploadFailed: file:" +
              uploadInfo.file.name +
              ",code:" +
              code +
              ", message:" +
              message
          );
        },
        // 文件上传进度，单位：字节
        onUploadProgress: function(uploadInfo, totalSize, loadedPercent) {
          console.log(
            "onUploadProgress:file:" +
              uploadInfo.file.name +
              ", fileSize:" +
              totalSize +
              ", percent:" +
              Math.ceil(loadedPercent * 100) +
              "%"
          );
          // $("#jindu").html("percent:" + Math.ceil(loadedPercent * 100) + "%");
             _this.$loadingshowjindu(Math.ceil(_this.piccount/2 * 100) + "%")
        },
        // 上传凭证超时
        onUploadTokenExpired: function(uploadInfo) {
          console.log("onUploadTokenExpired");
          //上传方式1  实现时，根据uploadInfo.videoId调用刷新视频上传凭证接口重新获取UploadAuth
          // uploader.resumeUploadWithAuth(uploadAuth);
          // 上传方式2 实现时，从新获取STS临时账号用于恢复上传
          // uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expireTime);
        },
        //全部文件上传结束
        onUploadEnd: function(uploadInfo) {
          console.log("onUploadEnd: uploaded all the files");
        }
      });
    },
    closethumb(){
     console.log('点击事件探测到了')
      var tr= document.getElementsByClassName('pan-thumb')[0].style.transform;
         console.log('css: '+tr)
      if(tr=='unset')

       {  document.getElementsByClassName('pan-thumb')[0].style.transform='rotate(-110deg)';
            // document.getElementsByClassName('pan-thumb')[0].style.transform='';
       }
         else  if(tr=='rotate(-110deg)')
        {
          document.getElementsByClassName('pan-thumb')[0].style.transform='unset';
          // document.getElementsByClassName('pan-thumb')[0].style.transform='';
        }  
        // else if(tr=='')
        //  document.getElementsByClassName('pan-thumb')[0].style.transform='unset';
    },

         changephoto(){
           console.log('change photo')
        },
        
        // 上传裁剪好的头像
         uploadAvatar(src) {
                      console.log('确认2')
                this.$loadingshow();
           console.log('接收到裁剪后的图片了')
           this.imgSrccut = src;
           //对小图需要进行压缩
           var _this=this;
           function goupload(resizefile){
   _this.showCutter = false;
           var imgori=_this.imgSrc;
           //裁剪后
         var userData =
          '{"Vod":{"StorageLocation":"","Title":"this is title.我是标题","Description":"this is desc.我是描述","CateId":"19","index":"1","Tags":"tag1,tag2,标签3","fengmian":"http://www.baidu.com"}}';
                //裁剪前
                var userData2 =
          '{"Vod":{"StorageLocation":"","Title":"this is title.我是标题","Description":"this is desc.我是描述","CateId":"19","index":"2","Tags":"tag1,tag2,标签3","fengmian":"http://www.baidu.com"}}';
       
  _this.uploader.addFile(
         resizefile,
          null,
          null,
          null,
          userData
        );
       _this.uploader.addFile(
         imgori,
          null,
          null,
          null,
          userData2
        );
    
     
     _this.piccount=0;
      _this.uploader.startUpload();

           }
       this.resize(src,70,70,goupload)
        
            




        },
        resize(file,width,height,reply){
          

 
var reader = new FileReader(), img = new Image();

// 选择的文件对象
 reader.readAsDataURL(file);    
// 文件base64化，以便获知图片原始尺寸
reader.onload = function(e) {
    img.src = e.target.result;
};
// 缩放图片需要的canvas
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
 
// base64地址图片加载完毕后
var that=this;
img.onload = function () {
    // 图片原始尺寸
    var originWidth = this.width;
    var originHeight = this.height;
    // 最大尺寸限制
    var maxWidth = width, maxHeight = height;
    // 目标尺寸
    var targetWidth = originWidth, targetHeight = originHeight;
    // 图片尺寸超过400x400的限制
    if (originWidth > maxWidth || originHeight > maxHeight) {
        if (originWidth / originHeight > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
        } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
        }
    }
        
    // canvas对图片进行缩放
    canvas.width = targetWidth;
    canvas.height = targetHeight;
    // 清除画布
    context.clearRect(0, 0, targetWidth, targetHeight);
    // 图片压缩
    context.drawImage(img, 0, 0, targetWidth, targetHeight);
    var result=canvas.toDataURL();
    var resizeimagecut=that.base64ToFile(result, 'resize.png')
      reply(resizeimagecut);

}




        }
        
  }
  
};
</script>

<style lang="scss" scoped>
/deep/ .el-card.is-always-shadow {
  box-shadow: unset;
}
/deep/ .van-overlay{
    background-color: rgba(0,0,0,.3);
}
/deep/ .el-card {
  border: unset;
}
.box-center {
  margin: 0 auto;
  display: table;
}

.text-muted {
  color: #777;
  word-break: break-all;
}

.user-profile {
  .user-name {
    font-weight: bold;
  }

  .box-center {
    padding-top: 10px;
  }

  .user-role {
    padding-top: 10px;
    font-weight: 400;
    font-size: 14px;
  }

  .box-social {
    padding-top: 30px;

    .el-table {
      border-top: 1px solid #dfe6ec;
    }
  }

  .user-follow {
    padding-top: 20px;
  }
}

.user-bio {
  margin-top: 20px;
  color: #606266;

  span {
    padding-left: 4px;
  }

  .user-bio-section {
    font-size: 14px;
    padding: 15px 0;

    .user-bio-section-header {
      border-bottom: 1px solid #dfe6ec;
      padding-bottom: 10px;
      margin-bottom: 10px;
      font-weight: bold;
    }
  }
}
.nosign{
    width: 150px;
    height: 30px;
    background: cornflowerblue;
    font-size: 14px;
    color: #fff;
    line-height: 30px;
    border-radius: 10px;
    text-align: center;
    margin: 0 auto;
    margin-top: 20px;
}
.sign{
    width: 80px;
    height: 30px;
    border: #777;
    background: #dfe6ec;
    font-size: 14px;
    color: #000;
    line-height: 30px;
    border-radius: 10px;
    text-align: center;
    margin: 0 auto;
    position: relative;
    /* margin-top: 20px; */
    bottom: 25px;
    float: right;
}
.userfile{
    width: 90px;
    height: 30px;
    background: cornflowerblue;
    font-size: 14px;
    color: #fff;
    line-height: 30px;
    border-radius: 10px;
    text-align: center;
    margin: 0 auto;
    margin-top: 20px;
}
.userfile1{
    width: 90px;
    height: 30px;
    background: lightseagreen;
    font-size: 14px;
    color: #fff;
    line-height: 30px;
    border-radius: 10px;
    text-align: center;
    margin: 0 auto;
    margin-top: 20px;
}
.userfile2{
    width: 90px;
    height: 30px;
    background: chocolate;
    font-size: 14px;
    color: #fff;
    line-height: 30px;
    border-radius: 10px;
    text-align: center;
    margin: 0 auto;
    margin-top: 20px;
}
.userm{
  display: flex;
  justify-content: space-around;
}
img{
        display: block;
        width: 120px;
        height: 120px;
    }
    h3{
        text-align: center;
    }
    h1, h2 {
      font-weight: normal;
    }
    ul {
      list-style-type: none;
      padding: 0;
    }
    li {
      display: inline-block;
      margin: 0 10px;
    }
    a {
      color: #42b983;
    }
</style>
